<?php

namespace catchAdmin\api\controller;

use cainiao\api\v1\Link;
use catchAdmin\externalGoods\model\Category;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\TenantGoods;
use catchAdmin\externalGoods\model\TenantGoodsRule;
use catchAdmin\externalGoods\model\TenantGoodsAttr;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use think\helper\Str;
use think\Request;
use think\facade\Request as ThinkRequest;
/*
 *
 * */
class Goods extends Index
{
    public function goodsService(Request $request)
    {
        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('HouNiao',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token



//            if(!$request->has('data','post')){
//                return $this->commonReturn('goods',['code'=>Code::FAILED, 'msg'=>'缺少data']);
//            }
//
//            //处理data
//            $data = json_decode($data,true);
//            if(!$data||!is_array($data)){
//                return $this->commonReturn('goods',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
//            }

            //方法分发
            switch ($serviceType)
            {
                //接收订单
                case 'get_list':
                    $result = $this->getList();
                    break;
                case 'get_info':
                    $result = $this->getInfo();
                    break;
                case 'get_spec':
                    $result = $this->getSpec();
                    break;
                case 'get_info_batch':
                    $result = $this->getInfoBatch();
                    break;
                case 'create_goods':
                    $result = $this->createGoods();
                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn("HouNiao:" . $serviceType,$result);

        } catch (\Exception $exception) {
            return $this->commonReturn("HouNiao:" . $serviceType,['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }

    }


    //创建商品
    protected function createGoods(){
        $request = (new ThinkRequest);
        $data = $request::post();

        //定义三个模型 商品、属性、规格
        $tenantGoodsModel = new TenantGoods();  
        $tenantGoodsAttrModel = new TenantGoodsAttr();
        $tenantGoodsRuleModel = new TenantGoodsRule();

        //判断商品是否存在
        $goods = $tenantGoodsModel->where('goods_spu',$data['goods_spu'])->find();
        //存在就删除商品表，属性表，和规格表
        if($goods){
            $tenantGoodsModel->where('goods_spu',$data['goods_spu'])->delete();
            $tenantGoodsAttrModel->where('goods_id',$goods['id'])->delete();
            $tenantGoodsRuleModel->where('goods_id',$goods['id'])->delete();
        }

//        "attr": [
//            {
//                "attr_name": "规格",
//                "attr_value": "默认规格"
//            }
//        ],
//        "rule": [
//            {
//                "sku_val": "默认规格",
//                "sku_market_price": "6148.50",
//                "sku_price": 0,
//                "sku_stock": 0,
//                "sku_id": "2047300882767708928",
//                "pr_name": "规格",
//                "shelves_status": 0,
//                "sku_name": "规格:默认规格"
//            }
//        ]

        //创建商品
        $tenantGoodsModel->create($data);

        //批量新增属性
        $attr = [];
        foreach($data['attr'] as $v){
            $attr[] = [
                'goods_id' => $tenantGoodsModel->id,
                'attribute_id' => $v['attr_name'],
                'name' => $v['attr_value'],
                'attribute_name' => $v['attr_name'],
                'tenant_id' => $this->merchantInfo['tenant_id'],
                'goods_spu' => $data['goods_spu'],
            ];
        }
        $tenantGoodsAttrModel->insertAll($attr);

        // 批量创建规格
        $rule = [];
        foreach($data['rule'] as $v){
            $rule[] = [
                'goods_id' => $tenantGoodsModel->id,
                'goods_spu' => $data['goods_spu'],
                'goods_sku' => $v['sku_id'],
                'spec_sku' => $v['sku_val'],
                'sku_name' => $v['sku_name'],
                'sku_price' => $v['sku_price'],
                'sku_stock' => $v['sku_stock'],
                'sku_market_price' => $v['sku_market_price'],
                'tenant_id' => $this->merchantInfo['tenant_id'],
            ];
        }
        $tenantGoodsRuleModel->insertAll($rule);
        return ['code'=>Code::SUCCESS, 'msg' => '商品创建成功'];
    }


    //商品列表
    protected function getList()
    {
        if(ThinkRequest::param('limit') > 200){
            return [ 'code'=>Code::FAILED , 'msg'=> '分页条数，默认10，最大值200' ];
        }

        $tenantGoodsModel = new TenantGoods();

        return ['code'=>Code::SUCCESS, 'msg' => '获取列表成功', 'data' => $tenantGoodsModel->apiGetList($this->merchantInfo['tenant_id'])];
        //return CatchResponse::paginate($tenantGoodsModel->getList($this->merchantInfo['tenant_id']));
    }

    //商品详情
    protected function getInfo()
    {
        //$tenantGoodsModel = new TenantGoods();
        $request = (new ThinkRequest);
        $goods_spu =  $request::post('goods_spu');

        $goods = (new TenantGoods())
            ->field('goods_spu,
            id,
            syst_goods_id,
            goods_name,
            goods_subtitle,
            goods_keywords,
            goods_img,
            goods_slideshow_img,
            barcode,
            brand_id,
            brand_name,
            origin_id,
            origin_name,
            trade_type_id,
            trade_type_name,
            unit_id,
            unit_name,
            is_sale,
            category_id,
            sync_category_id_path as category_id_path,
            sync_category_name as category_name,
            description,
            price,
            stock')
            ->where('goods_spu',$goods_spu)
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->find();
        if(!$goods){
            return [ 'code'=>Code::FAILED , 'msg'=> '商品不存在' ];
        }

        if($goods['category_name'] == ''){ //处理有些商品没有分类问题
            $goods['category_name'] = json_encode((new Category)->where('id',$goods['category_id'])->find()->cate_name_arr ?? [] ,JSON_UNESCAPED_UNICODE);
        }

        $goods['goods_pic'] = $goods['goods_img'];//主图
        $goods_slideshow_img = array_merge([$goods['goods_pic']], json_decode($goods['goods_slideshow_img'],true));
        $goods['goods_slideshow_img'] =$goods_slideshow_img;//轮播图包含主图

        //
        $goods['attr'] = (new TenantGoodsAttr)
            ->field('attribute_id,name,attribute_name')
            ->where('goods_id',$goods['id'])->select()->toArray();
        $goods['rule'] = (new TenantGoodsRule)
            ->field('goods_sku,spec_sku,sku_name,sku_attribute_id,sku_attribute_name,sku_price,sku_stock')
            ->where('goods_id',$goods['id'])->select()->toArray();

        return ['code'=>Code::SUCCESS, 'msg' => '商品详情获取成功', 'data' => $goods];
        //return CatchResponse::paginate($tenantGoodsModel->getList($this->merchantInfo['tenant_id']));
    }

    //商品规格
    protected function getSpec(){
        //$tenantGoodsModel = new TenantGoods();
        $request = (new ThinkRequest);
        $goods_spu =  $request::post('goods_spu');

        $goods = (new TenantGoods())
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('goods_spu',$goods_spu)->find();
        if(!$goods){
            return [ 'code'=>Code::FAILED , 'msg'=> '商品不存在' ];
        }

        if(0 == $goods->is_sale){//下架的商品
            return [ 'code'=>Code::FAILED , 'msg'=> '当前商品处于下架状态。商品sku_list不存在或库存不足，建议下架该商品' ];
        }

        $result = [];
        $result['attr'] = (new TenantGoodsAttr)
            ->field('attribute_id,name,attribute_name')
            ->where('goods_id',$goods['id'])
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->select()->toArray();
        $result['rule'] = (new TenantGoodsRule)
            ->field('goods_sku,spec_sku,sku_name,sku_attribute_id,sku_attribute_name,sku_price,sku_stock')
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('goods_id',$goods['id'])->select()->toArray();

        return ['code'=>Code::SUCCESS, 'msg' => '商品规格获取成功', 'data' => $result];
    }

    protected function getInfoBatch()
    {
        $request = (new ThinkRequest);
        $goods_spu =  $request::post('goods_spu_batch');

        if(empty($goods_spu)){
            return [ 'code'=>Code::FAILED , 'msg'=> '参数错误' ];
        }

        if(200 <  count(explode(',',$goods_spu))){
            return [ 'code'=>Code::FAILED , 'msg'=> '最大上限值200条' ];
        }

        $tenantGoodsModel = new TenantGoods();

        return ['code'=>Code::SUCCESS, 'msg' => '批量获取商品列表成功', 'data' => $tenantGoodsModel->apiGetList($this->merchantInfo['tenant_id'],false)];
        //return CatchResponse::paginate($tenantGoodsModel->getList($this->merchantInfo['tenant_id']));
    }
}